package sample.util;

import javafx.geometry.Orientation;
import javafx.geometry.Pos;
import javafx.scene.control.*;
import javafx.scene.input.KeyCode;
import javafx.scene.layout.VBox;
import javafx.scene.web.WebView;
import javafx.stage.Stage;

import java.net.MalformedURLException;
import java.util.concurrent.atomic.AtomicInteger;

/**

 * @name      :WebScrollPane

 * @Description: for website scroll pane which extends the basic ScrollPane

*/
public class WebScrollPane extends ScrollPane {
    public final static String mainPage="https://gitee.com/HughNew/relax-box";
    public final static String Bing="https://cn.bing.com/search?q=";
    public final static String Baidu="https://www.baidu.com/s?wd=";
    public final static String NotFound="<h1 class=\"center\" style=\"color: red\">Page not Found or no Network connected</h1>";

    // baidu bing google
    AtomicInteger engNum;
    WebView View;
    Stage root;
    public WebScrollPane(){
        this(null);
    }
    public WebScrollPane(Stage s){
        super();
        this.root=s;
        View = new WebView();
        this.setContent(View);
    }
    private void searchHelp(engine eg){
        switch(eg){
            case google -> this.load(WebScrollPane.localGooglePage());
            case main -> this.load(WebScrollPane.localMain());
            case start -> this.init();
        }
    }
    private void searchHelp(String content,engine eg){
        switch(eg){
            case bing -> this.load(Bing+content);
            case baidu -> this.load(Baidu+content);
            case raw -> this.load(content);
            case google -> this.load(WebScrollPane.localGooglePage());
            case main -> this.load(WebScrollPane.localMain());
        }
    }
    public WebScrollPane search(String content,engine eg){
        this.searchHelp(content,eg);
        return this;
    }
    public WebScrollPane search(String content,engine eg,Stage stage){
        this.searchHelp(content,eg);
        this.setStage(stage).fitStageSize();
        return this;
    }
    public WebScrollPane search(engine eg){
        this.searchHelp(eg);
        return this;
    }
    public WebScrollPane search(engine eg,Stage stage){
        this.searchHelp(eg);
        this.setStage(stage).fitStageSize();
        return this;
    }
    private void load(String s){
        this.setContent(View);
//        URL url;
//        try {
//            url = new URL(s);
//            URLConnection oc = url.openConnection();
//            oc.setUseCaches(false);
//            View.getEngine().load(new java.io.File("src/html/base.html").toURI().toURL().toString());
//            oc.setConnectTimeout(3000); // 设置超时时间
//        }catch(IOException e){
//            View.getEngine().loadContent(NotFound);
//            return;
//        }
//        View.getEngine().load(url.toString());
        View.getEngine().load(s);
        this.fitStageSize();
    }
    public void fitStageSize(){
        fitStageSize(1000);
    }
    public void fitStageSize(int wid){
        if(this.root!=null){
            this.root.setWidth(wid);
            this.root.setHeight(600);
            this.setWidth(this.root.getWidth());
            this.View.setPrefWidth(this.root.getWidth());
        }
    }
    public WebScrollPane setStage(Stage stage){
        if (stage!=null)
            this.root=stage;
        return this;
    }
    public static String localGooglePage(){
        try {
            return new java.io.File("src/html/404.html").toURI().toURL().toString();
        } catch (MalformedURLException e) {
            return "www.google.com";
        }
    }
    public static String localMain(){
        try {
            return new java.io.File("src/html/index.html").toURI().toURL().toString();
        } catch (MalformedURLException e) {
            return mainPage;
        }
    }
    public static int bool2HalfPI(boolean b){
        return b?180:0;
    }
    private void itemAction(SplitPane sp,int index){
        ((Button)sp.getItems().get(index)).setOnAction(e->{
            if(engNum.get()!=index){
                ((Button)sp.getItems().get(index)).getGraphic().setRotate(180);
                ((Button)sp.getItems().get(engNum.get())).getGraphic().setRotate(0);
                engNum.set(index);
            }
        });
    }
    public void init(){
        engNum=new AtomicInteger(1);
        SplitPane sp=new SplitPane();
        sp.setOrientation(Orientation.HORIZONTAL);
        try {
            sp.getItems().add(ButtonGenerator.SubButton("baidu"));
            sp.getItems().add(ButtonGenerator.SubButton("bing"));
            sp.getItems().add(ButtonGenerator.SubButton("google"));
            itemAction(sp,0);
            itemAction(sp,1);
            itemAction(sp,2);
            ((Button)sp.getItems().get(1)).getGraphic().setRotate(180);
        }catch(MalformedURLException ignored){}
        Button bt=new Button();
        bt.setGraphic(new TextField());
        TextField tf=(TextField)bt.getGraphic();
        tf.setEditable(true);
        tf.setPromptText("Input the keyword and Press Enter to search");
        tf.setMinWidth(800);
        bt.getGraphic().setOnKeyPressed(e->{
            if(e.getCode()== KeyCode.ENTER){
                this.search(((TextField)bt.getGraphic()).getText(),num2engine());
            }
        });
        bt.setContentDisplay(ContentDisplay.LEFT);
        bt.setOnAction(e->{
            this.search(((TextField)bt.getGraphic()).getText(),num2engine());
        });
        VBox vb=new VBox(sp,bt);
        vb.setAlignment(Pos.CENTER);
        this.setContent(vb);
//        ((TextField)bt.getGraphic()).setMinWidth(this.getWidth());
    }
    public void searchBarRequestFocus(){
        if(this.getContent() instanceof VBox)
            (((Button)((VBox) this.getContent()).getChildren().get(1)).getGraphic()).requestFocus();
    }
    private engine num2engine(){
        return switch(engNum.get()){
            case 0 -> engine.baidu;
            case 1 -> engine.bing;
            case 2 -> engine.google;
            default -> engine.start;//impossible here
        };
    }
}
